package com.macaline.technology.rabbitMq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class MQConsumer {

	/**
	 * 创建mq的接收消息并处理的实体类
	 *
	 * @author warm_joy
	 * @param queueName
	 * @param action
	 * @throws IOException
	 * @throws TimeoutException
	 */
	public MQConsumer(String queueName, MqConsumerProcessor action) throws IOException, TimeoutException {
		recrviceMsg(queueName, action);
	}

	/**
	 * 接收MQ消息并进行消息处理
	 * @author warm_joy
	 * @param queueName 队列名称
	 * @param action    进行消息处理的逻辑接口
	 * @throws IOException
	 * @throws TimeoutException
	 */
	public static void recrviceMsg(String queueName, MqConsumerProcessor action) throws IOException, TimeoutException {
		Connection connection = RabbitMqUtil.getConnection();
		Channel channel = connection.createChannel();
		channel.queueDeclare(queueName, true, false, false, null);
		DefaultConsumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				String msg = new String(body);
				action.messageProcessor(msg);
			}
		};
		channel.basicConsume(queueName, true, consumer);
	}

	public static void main(String[] args) throws IOException, TimeoutException {
		new MQConsumer("queue001", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue001：" + msg);
			}
		});

		new MQConsumer("queue002", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue002:" + msg);
			}
		});
		new MQConsumer("queue003", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue003" + msg);
			}
		});
		new MQConsumer("queue004", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue004:" + msg);
			}
		});
		new MQConsumer("queue005", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue005:" + msg);
			}
		});
		new MQConsumer("queue006", new MqConsumerProcessor() {

			@Override
			public void messageProcessor(String msg) {
				// TODO Auto-generated method stub
				System.out.println("queue006:" + msg);
			}
		});
	}
}
